/**
 * 项目管理--js
 * 
 * @author cl
 */
var data_project = {
	MODULE_ID : "",
	Table_Obj : null,// 表格对象
	 /**
	 * 用户数据集
	 */
	userData:[],
	
	init : function() {
		data_project.MODULE_ID = GetRequest().pid;
		data_project.loadData();
		data_project.loadUseData();
	},
	/**
	 * 初始化
	 */
	loadData : function() {
		var obj = data_project.getParam();
		$.ajax({
			url : "/crm/retrieval/comSearch", // 请求的url地址
			dataType : "json", // 返回格式为json
			async : false,// 请求是否异步，默认为异步，这也是ajax重要特性
			data : obj, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				data_project.initTable(data.rows);
				$("#total_records").text(data.total);
				$("#this_page").text(1);
				$("#total_page").text(data.totalPages);
				var url = "/crm/retrieval/comSearch";
				setCommon(obj, Table_Obj, url);
			},
			error : function() {
			}
		})
	},
	/**
	 * 检索获取条件
	 */
	getParam : function() {
		var obj = {};
		obj.pageIndex = 1;
		pageSize = $("#page_size").val();
		obj.pageSize = pageSize;
		obj.orderBy = "create_time";
		obj.orderDesc = 1;
		obj.table = "data_project";
		var text = $("#searchWords").val().replace(/ /g, '@#@');
		obj.text=text;
		var proStats = $("#proStats").val();
		if(proStats.trim().length==0){
			obj.higthText="";
		}else{
			obj.higthText="AND,pro_stats,"+proStats+",0";
		}
		return obj;
	},
	/**
	 * 初始化表格
	 */
	initTable:function(datas) {
		var esay = $("#TableContainer").easyTable({
			data : datas, // 初始数据，动态添加可以通过setData
			hideCheckbox : false, // 否显示复选框，获取复选框选择的数据用方法getCheckedItem
			clickChangeColor:false,//单击之后切换颜色，
			doubleClickChangeColor:true,//双击之后切换颜色，
			// rowClick : function(data) {// 行点击回调，参数为改行数据
			// alert(JSON.stringify(data))
			// },
			rowDoubleClick : function(data) {// 行双击回调，参数为改行数据
				data_project.lookDetail(data.uuid);
			},
			columns : [ {
				title : "名称",
				field : "pro_name"
			}, {
				title : "负责人",
				field : "liable_user_name"
			}, {
				title : "小组成员",
				field : "team_members_names"
			}, {
				title : "状态",
				field : "pro_stats",
				render : function(data) {
					return data.pro_stats==0?"正常":"终止";
				}
			}, {
				title : "开始时间",
				field : "begin_time"
			}, {
				title : "下一节点时间",
				field : "next_step_time"
			}, {
				title : "创建时间",
				field : "create_time"
			}, {
				title : "操作",
				render : function(data) {
					return data_project.loadOperater(data);
				}
			} ]
		});
		Table_Obj = esay;
	},
	/**
	 * 加载方法
	 * 
	 * @param data
	 * @returns {String}
	 */
	loadOperater:function(data) {
		var html = "";
		html += '<a onclick="data_project.lookDetail(\'' + data.uuid + '\',this)">查看</a>';
		if(data.pro_stats==0){
			html += '<a class="ml10" onclick = "data_project.empower(\'' +data.uuid+ '\')">授权</a>';
			html += '<a class="ml10" onclick="data_project.edit(' + data.id + ')">编辑</a>';
			html += '<a class="ml10" onclick="data_project.setLiableUser(\'' + data.uuid + '\',\'' + data.liable_user_uuid + '\')">重置责任人</a>';
			html += '<a class="ml10" onclick="data_project.startOrEnd(\'' + data.uuid + '\',\'1\')">终止</a>';
		}else{
			html += '<a class="ml10" onclick="data_project.startOrEnd(\'' + data.uuid + '\',\'0\')">恢复</a>';
		}
		html += '<a class="ml10" onclick="data_project.deleteThis(' + data.id + ')">删除</a>';
		return html;
	},
	/**
	 * 检索user
	 */
	searchData:function() {
		var pageSize = $("#page_size").val();
		var pageIndex = 1;
		var obj = {};
		obj.pageSize = pageSize;
		obj.pageIndex = pageIndex;
		var othr = data_project.getParam();
		reset_serach(othr, obj);
	},
	changeStats:function(){
		var proStats = $("#proStats").val();
		if(proStats.trim().length==0){
			$("#ed_btn_1").hide();
			$("#ed_btn_2").hide();
			$("#ed_btn_3").hide();
			$("#ed_btn_4").hide();
		}else if(proStats=="0"){
			$("#ed_btn_1").show();
			$("#ed_btn_2").hide();
			$("#ed_btn_3").show();
			$("#ed_btn_4").show();
		}else{
			$("#ed_btn_1").hide();
			$("#ed_btn_2").show();
			$("#ed_btn_3").hide();
			$("#ed_btn_4").hide();
		}
		data_project.searchData();
	},
	/**
	 * 创建项目
	 */
	addSave:function(){
		parent.createPage("创建项目", "../html/project/create_project.html", true, "create_project");
//		window.location.href="/crm/html/project/create_project.html";
	},
	/**
	 * 查看详情
	 * 
	 * @param twq
	 */
	lookDetail:function(id,_this) {
		$(_this).parent().parent("tr").css("color", "red");
		parent.createPage("项目详情", "../html/project/project_detail.html?uuid=" + id, true, "project_detail");
//		window.location.href="/crm/html/project/project_detail.html?id=" + id;
	},
	/**
	 * 编辑项目
	 */
	edit:function(id){
		parent.createPage("编辑项目", "../html/project/edit_project.html?id=" + id, true, "edit_project");
//		window.location.href="/crm/html/project/edit_project.html?id=" + id;
	},
	/**
	 * 删除操作
	 */
	deleteThis:function(id) {
		layer.confirm('确定要删除吗?',{btn: ['确定', '取消'],title:"提示"}, function(){
			layer.confirm('再次确认', {btn : ['确定', '取消'], title:"提示"}, function() {
				$.ajax({
					type: "post",
					url: "/crm/project/physicalDeleteByIds",
					data: {
						ids:id
					},
					dataType: "json",
					async:false,
					success:function(data) {
						if(data.status){
							var index=layer.alert(data.info+"请稍后刷新查看！", {icon: 1},function(){
								data_project.searchData();
								layer.close(index);
							});

						}else{
							layer.msg(data.info, {icon: 2});
						}
					}
				});
			});
	    });
	},
	beacthDelete:function() {
		var datas = Table_Obj.getCheckedItem();
		if (datas.length == 0) {
			layer.alert("未选择有效数据！", "");
			return;
		}
		var arr = new Array();
		$.each(datas, function(key, val) {
			arr[key] = val.id;
		});
		var ids = arr.join(",");
		data_project.deleteThis(ids)
	},
	/**
	 * 恢复或者终止
	 */
	startOrEnd:function(uuids,isEnd){
		layer.confirm(isEnd==0?"确认恢复操作？":"确认终止操作？",{btn: ['确定', '取消'],title:"提示"}, function(){
            layer.confirm('再次确认', {btn : ['确定', '取消'], title:"提示"}, function() {
        		var obj={};
        		obj.uuids = uuids;
        		obj.isEnd = isEnd;
            	$.ajax({
                    type: "post",
                    url: "/crm/project/setProjectStartOrEnd",
                    data: obj,
                    dataType: "json",
                    async:false,
                    success:function(data) {
                        if(data.status){
                            var index=layer.alert(data.info+"，请6-30秒刷新后再查看！", {icon: 1},function(){
                                layer.close(index);
                                data_project.searchData();
                            });

                        }else{
                            layer.msg(data.info, {icon: 2});
                        }
                    }
                });
            });
	    });
	},
	/**
	 * 批量终止恢复
	 * @param isEnd
	 */
	batchStartOrEnd:function(isEnd) {
		var datas = Table_Obj.getCheckedItem();
		if (datas.length == 0) {
			layer.alert("未选择有效数据！", "");
			return;
		}
		var arr = new Array();
		$.each(datas, function(key, val) {
			arr[key] = val.uuid;
		});
		var uuids = arr.join(",");
		data_project.startOrEnd(uuids,isEnd);
	},
	/**
	 * 加载可用用户
	 * 1、可以，0、不可用
	 */
	loadUseData:function(){
		$.ajax({
			url : "/crm/user/loadUserByIsUse", // 请求的url地址
			dataType : "json", // 返回格式为json
			async : false,// 请求是否异步，默认为异步，这也是ajax重要特性
			data : {
				isUse:1
			}, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				data_project.userData = data;
			},
			error : function() {
			}
		})
	},
	/**
	 * 重置责任人
	 * @param uuid
	 */
	setLiableUser:function(uuid,liable_user_uuid){
		var html ="";
    	html+='<div class="js_ak"></div>';
    	
        layer.confirm(html, {btn : ['确定', '取消'],area:["550px","250px"], title:"重置责任人"}, function(){
        	var liable_user = $("input[name='role']:checked");
        	var obj = {};
        	obj.uuids = uuid;
        	obj.userUuid = liable_user.val();
        	obj.userName = liable_user.attr("data-name")
        	 $.ajax({
                 type: "post",
                 url: "/crm/project/resetLiableUserByUuids",
                 data: obj,
                 dataType: "json",
                 async:false,
                 success:function(data) {
                     if(data.status){
                         layer.alert(data.info+"请稍后刷新查看！", {icon: 1},function(index){
                         	data_project.searchData();
                             layer.close(index);
                         });

                     }else{
                         layer.msg(data.info, {icon: 2});
                     }
                 }
             });
        
        });
        
        var html = "";
		$.each(data_project.userData, function(key, val) {
			
			html += '<label>';
			html += '<input type="radio" name="role" hidden="hidden" value="'+val.uuid+'" data-name="'+val.userRealName+'"/>';
			html += '<a>'+val.userRealName+'</a>';
			html += '</label>';
		});
		$(".js_ak").html(html);
		$("input[name='role'][value='"+liable_user_uuid+"']").attr("checked",true); 
	},
	//--分开授予查看编辑 权限2019-04-22 开始
	empower : function(uuid) {
    	var html ="";
    	html += '<div class="cr_cont"><p>现小组成员：</p>';
    	html += '<input type="text" id="term_users" readonly="readonly"></div>';
    	html += '<p>人员授权：</p>';
    	html += '<div id="PowerTable" style="width: 98%; margin-left: 1%;"></div>';
        layer.confirm(html, {btn : ['确定', '取消'],area:["950px","450px"], title:"授权"}, function(){

        	var obj = {};
        	obj.uuids = uuid;
        	var xuuid = "";
        	var xname = "";
        	var ss = $("#PowerTable").find("input.A1:checked");
        	 $.each(ss, function(key, val) {
        		 xuuid += ","+ $(val).attr("data-id");
        		 xname += ","+ $(val).attr("data-name");
             });
    		obj.suuid = xuuid.substring(1);
    		obj.sname = xname.substring(1);
        		
        	 ss = $("#PowerTable").find("input.A2:checked");
        	 xuuid = "";
        	 xname = "";
        	 $.each(ss, function(key, val) {
        		 xuuid += ","+ $(val).attr("data-id");
        		 xname += ","+ $(val).attr("data-name");
             });
        	obj.euuid = xuuid.substring(1);
        	obj.ename = xname.substring(1);
            $.ajax({
                type: "post",
                url: "/crm/project/projectEmpowerByUuids",
                data: obj,
                dataType: "json",
                async:false,
                success:function(data) {
                    if(data.status){
                        layer.alert(data.info+"请稍后刷新查看！", {icon: 1},function(index){
                        	data_project.searchData();
                            layer.close(index);
                        });

                    }else{
                        layer.msg(data.info, {icon: 2});
                    }
                }
            });
        });
        data_project.initPowerTable(uuid);
    },
    
    /**
     * 权限表格对象
     */
    Table_power_obj : null,
    /**
     * 初始化权限表格
     * @param uuid
     */
	initPowerTable:function(uuid){
		var obj ={};
		obj.search_power_user_uuids="";
		obj.edit_power_user_uuids="";
		
		$.each(Table_Obj.getData(), function(key, val) {
			if(val.uuid==uuid){
				obj = val;
				$("#term_users").val(obj.team_members_names);
			}
		});
		console.log(obj)
		var esay = $("#PowerTable").easyTable({
			data : data_project.userData, // 初始数据，动态添加可以通过setData
			hideCheckbox : true, // 否显示复选框，获取复选框选择的数据用方法getCheckedItem
			// rowClick : function(data) {// 行点击回调，参数为改行数据
			// alert(JSON.stringify(data))
			// },
//			rowDoubleClick : function(data) {// 行双击回调，参数为改行数据
//				
//			},
			columns : [ {
				title : "用户",
				field : "userRealName"
			}, {
				title : "<input type='checkbox' onchange='data_project.opterChoos(1)' class='isSearch'>查看",
				field : "isSearch",
				//align : "right",
				render : function(data) {
					var str = obj.search_power_user_uuids.indexOf(data.uuid);
					if(str!= -1){ 
						d = '<input type="checkbox" data-id="'+data.uuid+'" data-name="'+data.userRealName+'" checked="checked" class="A1" id="search_'+data.uuid+'" onchange="data_project.opOnchange(\''+data.uuid+ '\',1,\''+data.userRealName+'\')">';
					} else {
						d = '<input type="checkbox"  data-id="'+data.uuid+'" data-name="'+data.userRealName+'" class="A1" id="search_'+data.uuid+'" onchange="data_project.opOnchange(\''+data.uuid+ '\',1,\''+data.userRealName+'\')">';
					}
					return d;
				}
			}, {
				title : "<input type='checkbox' onchange='data_project.opterChoos(2)' class='isEdit'>编辑",
				field : "isEdit",
				//align : "right",
				render : function(data) {
					var str = obj.edit_power_user_uuids.indexOf(data.uuid);
					if(str!= -1){ 
						d = '<input type="checkbox" data-id="'+data.uuid+'" data-name="'+data.userRealName+'" checked="checked" class="A2" id="edit_'+data.uuid+'" onchange="data_project.opOnchange(\''+data.uuid+ '\',2,\''+data.userRealName+'\')">';
					} else {
						d = '<input type="checkbox" data-id="'+data.uuid+'" data-name="'+data.userRealName+'" class="A2" id="edit_'+data.uuid+'" onchange="data_project.opOnchange(\''+data.uuid+ '\',2,\''+data.userRealName+'\')">';
					}
					return d;
				}
			}]
		});
		Table_power_obj = esay;
	},
	
	/**
	 *权限修改 操作(查看、编辑) 选中 取消
	 * 1.查看，2.编辑
	 * @author George
	 * @create time 2017/07/11
	 * @param tren
	 */
	opterChoos:function(tren) {
		var objs = Table_power_obj.getData();
		var isS = false;
		if (tren == 1) {
			isS = $(".isSearch").is(':checked');
			if (isS) {
				$(".A1").prop("checked", "checked");
			} else {
				$(".A1").removeAttr("checked");
				$(".A2").removeAttr("checked");
				$(".isSearch").removeAttr("checked");
				$(".isEdit").removeAttr("checked");
			}
		} else if (tren == 2) {
			isS = $(".isEdit").is(':checked');
			if (isS) {
				$(".A1").prop("checked", "checked");
				$(".A2").prop("checked", "checked");
				$(".isSearch").prop("checked", "checked");
			} else {
				$(".A2").removeAttr("checked");
				$(".isEdit").removeAttr("checked");
			}
		}
	},
	
	/**
	 * 权限切换
	 * @param uuid
	 * @param nu
	 */
	opOnchange:function(uuid, nu,name){
		var x1 = Table_power_obj.getData().length;
		var x2 = $("#PowerTable").find("input.A"+nu+":checked").length;
	
		if (nu == 1) {//查看
			if(x2==x1){
				$(".isSearch").prop("checked", "checked");
			}else{
				$(".isSearch").removeAttr("checked");
			}
			
			if (!$("#search_" + uuid + "").is(':checked')) {
				$("#edit_" + uuid + "").removeAttr("checked");
			}
		}
		
		if (nu == 2) {//编辑
			if(x2==x1){
				$(".isSearch").prop("checked", "checked");
				$(".isEdit").prop("checked", "checked");
			}else{
				$(".isEdit").removeAttr("checked");
			}
			
			if ($("#edit_" + uuid + "").is(':checked')) {
				$("#search_" + uuid + "").prop("checked", "checked");
			} 
		}
	},
	//--分开授予查看编辑权限 结束-------
    /**
     * 多项企业授权
     */
    batchEmpower : function() {
        var data = Table_Obj.getCheckedItem();
        if (data.length === 0) {
            layer.msg("未选择有效数据！");
            return;
        }
        var arr = [];
        $.each(data, function(key, val) {
            arr[key] = val.uuid;
        });
        var ids = arr.join(",");
        data_project.empower(ids)
    }
}
